#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

 typedef unsigned char  BYTE;
 typedef unsigned short WORD;
 typedef unsigned long  LONG;

 #define readw( x ) ( fgetc( x ) + (fgetc(x) << 8) )
 #define WRAM( x ) *(WORD *)&ram[ x ]
 #define LRAM( x ) *(LONG *)&ram[ x ]

 BYTE ram[0xFFFF],
      *p;

 BYTE buf[4][32];

 WORD valu;

 struct _REGZ{
   WORD y,
        x,
        a;
   BYTE stack;
 } reg;

 int  z;

 FILE *rf,
      *df;


  LONG Snes2Pc( LONG ofs );

int  main( )
{
  rf = fopen( "c:/romhack/trans/free6/LFan2.smc", "rb" );
  df = fopen( "c:/romhack/trans/free6/LFan2.myf", "wb" );

  if ( !rf || !df )
	{
    fcloseall( );
    return -1;
  }

  //
  z = -1;
  while( ++z < 0x0200 )
  {  // Amount of 8 - 16x16 Tiles

    fseek( rf, Snes2Pc( 0x8C9C00 + (z << 1) ), SEEK_SET );
    valu = readw( rf );

    // Decode the font
    LRAM( 0x1A ) = 0x10F4;
    LRAM( 0x1D ) = 0x10B4;
    //
    WRAM( 0x10AA ) = 0x0000;
    WRAM( 0x10AC ) = 0x0000;
    WRAM( 0x10AE ) = 0x0004;
    //
    WRAM( 0x10B0 ) = 0x0000;
    LRAM( 0x30 )   = Snes2Pc( 0x8C0000 + valu );
    //
    p = &ram[0x1A];
    reg.stack = 4;
    while( reg.stack > 0 )
    { //
      reg.y     = WRAM( 0x10AC );

      // Get to the font
      fseek( rf, LRAM( 0x30 ) + reg.y, SEEK_SET );
      ram[ 0x10B2 ] = fgetc( rf );
      //
      reg.y++;
      WRAM( 0x10AC ) = reg.y;
      //
      reg.x = 8;
      while( reg.x > 0 )
      { //

        // BIT set??
        if ( ram[ 0x10B2 ] & 1 )
  			{ //
          reg.y = WRAM( 0x10AE );
          fseek( rf, LRAM( 0x30 ) + reg.y, SEEK_SET );
          ram[ 0x10B0 ] = fgetc( rf );
          reg.y++;
          WRAM( 0x10AE ) = reg.y;
        }

	// BIT clear
        reg.y = WRAM( 0x10AA );
        reg.a = ram[ 0x10B0 ];
        // Store the data
        ram[ WRAM(0x1A) + reg.y ] = reg.a;
        ram[ WRAM(0x1D) + reg.y ] = reg.a;
        reg.y++;
        WRAM( 0x10AA ) = reg.y;
        //
        reg.x--;

        ram[ 0x10B2 ] >>= 1;
      }// WEND

      reg.stack--;
    } // WEND - stack


    // Store the tile
/*
    fwrite( &ram[ 0x10B4 + 0x00 ], 1, 0x20, df );
/*/
    fwrite( &ram[ 0x10B4 + 0x00 ], 1, 0x08, df );
    fwrite( &ram[ 0x10B4 + 0x10 ], 1, 0x08, df );
    fwrite( &ram[ 0x10B4 + 0x08 ], 1, 0x08, df );
    fwrite( &ram[ 0x10B4 + 0x18 ], 1, 0x08, df );
//*/
  }

  fcloseall( );

  return 0;
}



//-----------------------------//
// Load the program data Bank  //
//-----------------------------//
LONG Snes2Pc( LONG ofs )
{
  LONG val;

  if ( !ofs ) return 0;

  // SNES to ROM
  val = (((ofs | 0x800000) - 0x800000) & 0xFF0000) >> 1;
  val+= ((ofs & 0xFFFF) - 0x8000);

  return val;
}// END
